package com.basics.common.utils;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.core.Converter;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;

public class PaiConverter implements Converter {
    private static ObjectMapper objectMapperEx = new ObjectMapperEx();
    private final Logger log = LoggerFactory.getLogger(PaiConverter.class);

    public PaiConverter() {
    }

    public Object convert(Object value, Class target, Object context) {
        if (value != null && !(value instanceof NullNode)) {
            if (target.isAssignableFrom(JsonNode.class)) {
                if (!StringUtils.hasText(value.toString())) {
                    return null;
                } else {
                    try {
                        return objectMapperEx.readTree(value.toString());
                    } catch (Exception var5) {
                        this.log.error(MessageFormat.format("属性[{0}]的值从[{1}]转换成JsonNode失败：{2}，将返回null。", target.getName(), value.toString(), var5.getMessage()), var5);
                        return null;
                    }
                }
            } else if (value instanceof JsonNode && target.isAssignableFrom(String.class)) {
                return value.toString();
            } else {
                return !value.getClass().isAssignableFrom(target) && !target.isAssignableFrom(value.getClass()) ? null : value;
            }
        } else {
            return null;
        }
    }
}

